package log

import (
	"fmt"
	"io"
	"math/rand"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"github.com/buger/jsonparser"
	"github.com/sirupsen/logrus"
	prefixed "github.com/x-cray/logrus-prefixed-formatter"
)

var log = logrus.New()

func Init(level string, logFile *os.File) *logrus.Logger {
	formatter := new(prefixed.TextFormatter)
	formatter.TimestampFormat = "2006/01/02 15:04:05"

	// 设置颜色
	formatter.SetColorScheme(&prefixed.ColorScheme{
		PrefixStyle:    "blue",
		TimestampStyle: "blue",
	})
	// 指定日志的输出路径
	mw := io.MultiWriter(os.Stdout, logFile)
	log.SetOutput(mw)

	// 开启返回函数名和行号
	log.SetReportCaller(true)

	log.Formatter = formatter
	return log
}

// 接口
func Logger() *logrus.Logger {
	return log
}
func Info(a ...interface{}) {
	log.Info(a...)
}

func Warn(a ...interface{}) {
	log.Warn(a...)
}

func Error(a ...interface{}) {
	log.Error(a...)
}

func Fatal(a ...interface{}) {
	log.Fatal(a...)
}

func Infof(format string, a ...interface{}) {
	log.Infof(format, a...)
}

func Warnf(format string, a ...interface{}) {
	log.Warnf(format, a...)
}

func Errorf(format string, a ...interface{}) {
	log.Errorf(format, a...)
}

func Fatalf(format string, a ...interface{}) {
	log.Fatalf(format, a...)
}

func Debugf(format string, a ...interface{}) {
	log.Debugf(format, a...)
}
func fileName(name string) string {

	c := exec.Command("bash", "-c", "curl -s --unix-socket /run/docker.sock http://docker/containers/$HOSTNAME/json")
	if output, err := c.CombinedOutput(); err == nil && string(output) != "" {
		if containerName, err := jsonparser.GetString(output, "Name"); err == nil && containerName != "" {
			fmt.Println("容器名为", containerName)
			return containerName[1:] //去掉第一个字符："/""
		}
	}
	if name == "" {
		fmt.Println("未获取到容器名，使用程序名作为日志文件名")
		name = filepath.Base(os.Args[0])
		if len(os.Args) > 1 && !strings.Contains(os.Args[1], "config") {
			name = name + "_" + os.Args[1]
		}
	}

	rand.Seed(time.Now().UnixNano())
	name = name + "_" + strconv.Itoa(rand.Intn(1<<32))

	return name
}
func LogFile(dir, name string) (*os.File, error) {
	if fi, err := os.Stat(dir); err == nil {
		if !fi.IsDir() {
			return nil, fmt.Errorf("open %s: not a directory", dir)
		}
	} else if os.IsNotExist(err) {
		if err := os.MkdirAll(dir, 0766); err != nil {
			return nil, err
		}
	} else {
		return nil, err
	}
	loc, _ := time.LoadLocation("Asia/Shanghai")
	time.Local = loc
	var currenttime = time.Now().Format("2006-01-02_15.04.05")

	logfile, err := os.OpenFile(path.Join(dir, currenttime+"_"+fileName(name)+".log"), os.O_RDWR|os.O_CREATE, 0666)
	if err != nil {
		return nil, err
	}

	return logfile, nil
}
